<?php
declare (strict_types = 1);

namespace app\wework\listener;
use think\facade\Db;
use app\wework\model\CallbackModel;
use app\wework\model\QyWechatApi;
use app\wework\model\user\autogroup\AutoPullGroupModel;


class CustomerAutoCallback
{
    /**
     * 自动拉群 添加好友回调 回调
     * @return mixed
     */
    public function handle($event){
        if(!array_key_exists("State",$event))return "不是该渠道";
        if($event['State']){
            $auto = Db::table('kt_wework_group_auto')->where('state',$event['State'])->json(["staffs","upper","welcome_text"])->find();
            if(!$auto) return "不是该渠道";
            $wid = $auto["wid"];
            $staff = Db::table("kt_wework_staff")->where(["wid"=>$wid,"userid"=>$event['UserID']])->find();
            $statistics = Db::table("kt_wework_group_auto_statistics")->where(["wid"=>$wid,"staff_id"=>$staff["id"],"external_userid"=>$event["ExternalUserID"],"pid"=>$auto["id"]])->find();
            if(!$statistics){
                $statistics_data["wid"] = $wid;
                $statistics_data["staff_id"] = $staff["id"];
                $statistics_data["external_userid"] = $event["ExternalUserID"];
                $statistics_data["pid"] = $auto["id"];
                $statistics_data["ctime"] = date("Y-m-d H:i:s");
                $statistics_data["status"] = 1;
                Db::table("kt_wework_group_auto_statistics")->insert($statistics_data);
            }
            if($statistics)Db::table("kt_wework_group_auto_statistics")->where(["wid"=>$wid,"staff_id"=>$staff["id"],"external_userid"=>$event["ExternalUserID"],"pid"=>$auto["id"]])->update(["status"=>1]);
            if($auto["is_astrict"] == 1){
                $astrict = Db::table("kt_wework_group_auto_astrict")->where(["wid"=>$wid,"staff_id"=>$staff["id"],"pid"=>$auto["id"]])->find();
                $size = Db::table("kt_wework_group_auto_statistics")->where(["wid"=>$wid,"pid"=>$auto["id"],"staff_id"=>$staff["id"]])->count();
                if($astrict["size"] <= $size){
                    $staffs = $auto["staffs"];
                    $key = array_search($staff["id"],$staffs);
                    unset($staffs[$key]);
                    if($staffs){
                        $params['user'] = AutoPullGroupModel::users($staffs);
                        $params['config_id'] = $auto["config_id"];
                        $upd = QyWechatApi::updateContactWay($params,$wid);
                    }else{
                        //全部成员达到上限，开启备用成员
                        $update["standby_status"] = 1;
                    }
                    
                    if($upd["errcode"] != 0)return error("操作失败",$upd["errcode"]);
                    $upper = $auto["upper"]?:[];
                    array_push($upper,$staff["id"]);
                    $update["upper"] = $upper;
                    Db::table('kt_wework_group_auto')->where('state',$event['state'])->json(["upper"])->update($update);
                }
            }
            if($auto["is_tag"] == 1){
                $add_tag = json_decode($auto["tags"],1);
                $param = [
                    'userid' => $event['UserID'],
                    'external_userid' => $event['ExternalUserID'],
                    'add_tag' => $add_tag,
                    'remove_tag' => []
                ];
                if($add_tag){
                    $edit_tag = QyWechatApi::editMarkTag($param,$wid);
                    if($edit_tag["errcode"] == 0){
                        Db::table("kt_wework_customer")->where(["wid"=>$wid,"staff_id"=>$staff["id"],"external_userid"=>$event["ExternalUserID"]])->update(["tags"=>json_encode($add_tag,320),"tags_info"=>json_encode($add_tag,320)]);
                    }
                }
            }
            $group = Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"pid"=>$auto["id"],"status"=>1])->find();
            if($event['WelcomeCode']){
                $welcomeCode = $arr['WelcomeCode'];
                $msg = [
                    'text' => [
                        'content' => $auto['welcome_text'],
                    ]
                ];
                $msg["welcome_code"] = $welcomeCode;
                $msg["attachments"][] = [
                    "msgtype" => "image",
                    "image"=>[
                        "media_id"=>QyWechatApi::mediaUpload($wid,$group["code"],"image")
                    ]
                ];
                $res = QyWechatApi::sendWelcomeMsg($wid,$msg);
                return $res;
            }
        }
    }
}